//
//  MHTable+Query.m
//  数据库的读写封装
//
//  Created by zsgjs on 2017/2/21.
//  Copyright © 2017年 zsgjs. All rights reserved.
//

#import "MHTable+Query.h"

@implementation MHTable (Query)

- (id)queryNextValueField:(NSString *)field andWhere:(NSString *)where{
    
    NSDictionary *find = [self queryDictWithWhere:where];
    return [find objectForKey:field];
}

- (NSDictionary *)queryDictWithWhere:(NSString *)where
{
    [self.db clean];
    [self.db setCurrentTableName:self.tableName];
    if (![where isEqual:nil]) {
        [self.db whereWithString:where];
    }
    [self.db fieldsWithString:self.structure.fieldsString];
    return [self.db querySigleInfo];
}

- (NSArray *)queryWithWhere:(NSString *)where
{
    return [self queryWithWhere:where
                         fields:self.structure.fieldsString
                           page:0
                       pageSize:0
                          order:nil];
}

- (NSArray *)queryAll
{
    return [self queryWithWhere:@"1"];
}

- (NSArray *)queryAllValueWithFields:(NSString *)fields andWhere:(NSString *)where
{
    return [self queryWithWhere:where
                         fields:fields
                           page:0
                       pageSize:0
                          order:nil];
}

- (NSArray *)queryWithWhere:(NSString *)where
                     fields:(NSString *)fields
                       page:(NSUInteger)page
                   pageSize:(NSUInteger)pagesize
{
    return [self queryWithWhere:where
                         fields:fields
                           page:page
                       pageSize:pagesize
                          order:nil];
}

-(NSArray *)queryWithWhere:(NSString *)where
                    fields:(NSString *)fields
                      page:(NSUInteger)page
                  pageSize:(NSUInteger)pagesize
                     order:(NSString *)order
{
    
    [self.db clean];
    //tablename
    [self.db setCurrentTableName:self.tableName];
    if (pagesize >0) {
        int startNum = page<=0 ? 0:(int)((page -1)*pagesize);
        int endNum = (int)(page*pagesize);
        //limit
        [self.db limitWithStart:startNum End:endNum];
    }
    //where
    if (![where isEqual:nil]) {
        [self.db whereWithString:where];
    }
    //field
    if (![fields isEqual:nil]) {
        if ([fields isEqualToString:@"*"]) {
            [self.db fieldsWithString:self.structure.fieldsString];
        }
        else{
            [self.db fieldsWithString:fields];
        }
    }
    else{
        [self.db fieldsWithString:self.structure.fieldsString];
    }
    //order
    if (![order isEqual:nil]) {
        [self.db setOrder:order];
    }
    return  [self.db queryAll];
}

@end
